using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Spread.Common.Features.Sample;
using Spread.CellTypes.Data;
using FarPoint.Win.Spread.CellType;
using FarPoint.Win.Spread;
using FarPoint.Win.Spread.Model;

namespace Spread.CellTypes.Features
{
    public partial class CustomHeaderCells : BaseSampleControl
    {
        private DataTable _table;
        private int _ascii = 65;
        private char _character;
        private Random _random = new Random();
        public CustomHeaderCells()
        {
            InitializeComponent();
            Name = "Custom Header Cells";
            sheetView.DataAutoSizeColumns = false;
            sheetView.Columns.Default.Width = 90;
            sheetView.Rows.Default.Height = 25;

            sheetView.ColumnHeader.Rows[0].Height = 35;

            _table = new DataTable();

            for (int column = 1; column < 10; column++)
            {
                _character = (char)_ascii;
                _table.Columns.Add(new DataColumn() { ColumnName = _character.ToString(), DataType = typeof(Int32) });
                _ascii++;
            }
            for (int row = 0; row < 50; row++)
            {
                _table.Rows.Add(_random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200), _random.Next(-100, 200));
            }
            sheetView.DataSource = _table;

            ConditionalFormattingRule[] rules = new ConditionalFormattingRule[]
            {
                new UnaryComparisonConditionalFormattingRule(UnaryComparisonOperator.LessThan, 0, false)
                {
                    ForeColor = Color.Red, FontStyle = new SpreadFontStyle(RegularBoldItalicFontStyle.Bold)
                }
            };

            HideRowFilter hideRowFilter = new HideRowFilter(sheetView);
            Top10FilterItem top10FilterItem = new Top10FilterItem(true, 10, false);
            CustomFilterItem filterLessThan120 = new CustomFilterItem(new FilterCondition(CustomFilterOperatorType.GreaterThanOrEqual, 120),
                null, false);

            sheetView.ColumnHeader.Columns[1].CellType = new ColumnHeaderCellType(sheetView, new CheckBox()
            {
                Text = "< 0",
                TextAlign = ContentAlignment.MiddleCenter
            }, rules)
            { TooltipText = "Highlight negative numbers" };
            sheetView.ColumnHeader.Columns[3].CellType = new ColumnHeaderCellType(sheetView, new Button()
            {
                Text = "Top 10"
            }, hideRowFilter, top10FilterItem)
            { TooltipText = "Show Top 10 values" };
            sheetView.ColumnHeader.Columns[5].CellType = new ColumnHeaderCellType(sheetView, new CheckBox()
            {
                Text = ">= 120",
                TextAlign = ContentAlignment.MiddleCenter
            }, hideRowFilter, filterLessThan120)
            { TooltipText = "Values greater than 120" };
        }

        public class ColumnHeaderCellType : BaseCellType
        {
            private SheetView _sheet;
            private bool _active;
            private bool _filterAction;
            private ToolTip _toolTip;
            private bool _tooltipVisible;

            public Control Control { get; private set; }
            public IRowFilter RowFilter { get; set; }
            public BaseFilterItem FilterItem { get; set; }
            public ConditionalFormattingRule[] ConditionalFormattingRules { get; set; }
            public string TooltipText { get; set; }

            public ColumnHeaderCellType(SheetView sheet, Control control, IRowFilter rowFilter, BaseFilterItem filterItem)
                : this(sheet, control)
            {
                RowFilter = rowFilter;
                FilterItem = filterItem;
                _filterAction = true;
            }

            public ColumnHeaderCellType(SheetView sheet, Control control, ConditionalFormattingRule[] rule)
                : this(sheet, control)
            {
                _sheet = sheet;
                Control = control;
                ConditionalFormattingRules = rule;
                _filterAction = false;
            }

            private ColumnHeaderCellType(SheetView sheet, Control control)
            {
                _sheet = sheet;
                Control = control;
                _toolTip = new ToolTip();

                Control.Click += Control_Click;
                Control.MouseEnter += Control_MouseEnter;
                Control.MouseLeave += Control_MouseLeave;
            }

            private void Control_MouseEnter(object sender, EventArgs e)
            {
                if (!_tooltipVisible)
                {
                    _toolTip.Show(TooltipText, _sheet.FpSpread, new Point(Control.Left, Control.Bottom));
                    _tooltipVisible = true;
                }
            }

            private void Control_MouseLeave(object sender, EventArgs e)
            {
                _toolTip.Hide(_sheet.FpSpread);
                _tooltipVisible = false;
            }

            private void Control_Click(object sender, EventArgs e)
            {
                Point point = _sheet.FpSpread.PointToClient(MousePosition);
                HitTestInformation hitTestInfo = _sheet.FpSpread.HitTest(point.X, point.Y);
                int col = hitTestInfo.HeaderInfo.Column;

                if (_filterAction)
                {
                    if (_active)
                        ResetFilter(col);
                    else
                        ApplyFilter(col);
                }
                else
                {
                    if (_active)
                        RemoveFormattingRules(col);
                    else
                        AddFormattingRules(col);
                }

                _active = !_active;
            }

            private void ApplyFilter(int col)
            {
                FilterColumnDefinition fcd = new FilterColumnDefinition(col, FilterListBehavior.Custom);
                fcd.Filters.Add(FilterItem);
                RowFilter.ColumnDefinitions.Add(fcd);
                if (_sheet.RowFilter != RowFilter)
                    _sheet.RowFilter = RowFilter;
                _sheet.AutoFilterColumn(col, FilterItem.DisplayName, 0);
            }

            private void ResetFilter(int col)
            {
                _sheet.AutoFilterReset(col);
            }

            private void AddFormattingRules(int col)
            {
                RemoveFormattingRules(col);
                _sheet.SetConditionalFormatting(0, col, _sheet.RowCount, 1, true, ConditionalFormattingRules);
            }

            private void RemoveFormattingRules(int col)
            {
                var formattings = _sheet.GetConditionalFormatting(0, col, _sheet.RowCount, 1);
                if (formattings == null)
                    return;
                foreach (var formatting in formattings)
                    formatting.Clear();
            }

            public override string Format(object obj)
            {
                return string.Empty;
            }

            public override Control GetEditorControl(FarPoint.Win.Spread.Appearance appearance, float zoomFactor)
            {
                return null;
            }

            public override object GetEditorValue()
            {
                return null;
            }

            public override Size GetPreferredSize(Graphics g, Size size, FarPoint.Win.Spread.Appearance appearance, object value, float zoomFactor)
            {
                return new Size((int)(size.Width * zoomFactor), (int)(size.Height * zoomFactor));
            }

            public override void PaintCell(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
            {
                Control.Bounds = r;
                _sheet.FpSpread.Controls.Add(Control);
            }

            public override object Parse(string s)
            {
                return null;
            }

            public override void SetEditorValue(object value)
            {

            }
        }
    }
}


//
//CustomHeaderCells.Designer.cs
//


namespace Spread.CellTypes.Features
{
    partial class CustomHeaderCells
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            FarPoint.Win.Spread.FlatScrollBarRenderer flatScrollBarRenderer1 = new FarPoint.Win.Spread.FlatScrollBarRenderer();
            FarPoint.Win.Spread.FlatScrollBarRenderer flatScrollBarRenderer2 = new FarPoint.Win.Spread.FlatScrollBarRenderer();
            this.spread = new FarPoint.Win.Spread.FpSpread();
            this.sheetView = new FarPoint.Win.Spread.SheetView();
            this.pnlMain.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.spread)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.sheetView)).BeginInit();
            this.SuspendLayout();
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.spread);
            // 
            // spread
            // 
            this.spread.AccessibleDescription = "spread, CustomHeader, Row 0, Column 0";
            this.spread.Dock = System.Windows.Forms.DockStyle.Fill;
            this.spread.HorizontalScrollBar.Buttons = new FarPoint.Win.Spread.FpScrollBarButtonCollection("BackwardLineButton,ThumbTrack,ForwardLineButton");
            this.spread.HorizontalScrollBar.Name = "";
            flatScrollBarRenderer1.ArrowColor = System.Drawing.Color.FromArgb(((int)(((byte)(121)))), ((int)(((byte)(121)))), ((int)(((byte)(121)))));
            flatScrollBarRenderer1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
            flatScrollBarRenderer1.BorderActiveColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(171)))), ((int)(((byte)(171)))));
            flatScrollBarRenderer1.TrackBarBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(219)))), ((int)(((byte)(219)))), ((int)(((byte)(219)))));
            this.spread.HorizontalScrollBar.Renderer = flatScrollBarRenderer1;
            this.spread.Location = new System.Drawing.Point(0, 0);
            this.spread.Name = "spread";
            this.spread.Sheets.AddRange(new FarPoint.Win.Spread.SheetView[] {
            this.sheetView});
            this.spread.Size = new System.Drawing.Size(477, 487);
            this.spread.TabIndex = 0;
            this.spread.VerticalScrollBar.Buttons = new FarPoint.Win.Spread.FpScrollBarButtonCollection("BackwardLineButton,ThumbTrack,ForwardLineButton");
            this.spread.VerticalScrollBar.Name = "";
            flatScrollBarRenderer2.ArrowColor = System.Drawing.Color.FromArgb(((int)(((byte)(121)))), ((int)(((byte)(121)))), ((int)(((byte)(121)))));
            flatScrollBarRenderer2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
            flatScrollBarRenderer2.BorderActiveColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(171)))), ((int)(((byte)(171)))));
            flatScrollBarRenderer2.TrackBarBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(219)))), ((int)(((byte)(219)))), ((int)(((byte)(219)))));
            this.spread.VerticalScrollBar.Renderer = flatScrollBarRenderer2;
            // 
            // sheetView
            // 
            this.sheetView.Reset();
            this.sheetView.SheetName = "CustomHeader";
            // Formulas and custom names must be loaded with R1C1 reference style
            this.sheetView.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;
            this.sheetView.ColumnFooter.DefaultStyle.BackColor = System.Drawing.Color.Empty;
            this.sheetView.ColumnFooter.DefaultStyle.ForeColor = System.Drawing.Color.Empty;
            this.sheetView.ColumnFooterSheetCornerStyle.BackColor = System.Drawing.Color.Empty;
            this.sheetView.ColumnFooterSheetCornerStyle.ForeColor = System.Drawing.Color.Empty;
            this.sheetView.ColumnHeader.DefaultStyle.BackColor = System.Drawing.Color.Empty;
            this.sheetView.ColumnHeader.DefaultStyle.ForeColor = System.Drawing.Color.Empty;
            this.sheetView.RowHeader.Columns.Default.Width = 35F;
            this.sheetView.RowHeader.DefaultStyle.BackColor = System.Drawing.Color.Empty;
            this.sheetView.RowHeader.DefaultStyle.ForeColor = System.Drawing.Color.Empty;
            this.sheetView.SheetCornerStyle.BackColor = System.Drawing.Color.Empty;
            this.sheetView.SheetCornerStyle.ForeColor = System.Drawing.Color.Empty;
            this.sheetView.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1;
            // 
            // CustomHeaderCells
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "CustomHeaderCells";
            this.pnlMain.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.spread)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.sheetView)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private FarPoint.Win.Spread.FpSpread spread;
        private FarPoint.Win.Spread.SheetView sheetView;
    }
}
